package com.ohuang.imghide.hidetank;

import android.graphics.Bitmap;
import android.graphics.Color;

import androidx.annotation.NonNull;

import com.ohuang.imghide.util.BitmapUtil;

public class BlackHideTank {

    public static Bitmap create(Bitmap bitmap, Bitmap bitmap2) {
        if (bitmap != null && bitmap2 != null) {
            int with = Math.max(bitmap.getWidth(), bitmap2.getWidth());
            int height = Math.max(bitmap.getHeight(), bitmap2.getHeight());
            return getBitmap(bitmap, bitmap2, with, height);
        }
        return null;
    }
    public static Bitmap create(Bitmap bitmap, Bitmap bitmap2,int with,int height) {
        if (bitmap != null && bitmap2 != null) {
            return getBitmap(bitmap, bitmap2, with, height);
        }
        return null;
    }


    private static Bitmap getBitmap(Bitmap bitmap, Bitmap bitmap2, int with, int height) {
        Bitmap scale = BitmapUtil.Scale(bitmap, with, height);
        Bitmap scale1 = BitmapUtil.Scale(bitmap2, with, height);
        int[] pix1=new int[with * height];
        int[] pix2=new int[with * height];
        int[] pix3=new int[with * height];
        scale.getPixels(pix1,0, with,0,0, with, height);
        scale1.getPixels(pix2,0, with,0,0, with, height);
        Bitmap bitmap1=Bitmap.createBitmap(with, height, Bitmap.Config.ARGB_8888);
        for (int i = 0; i < pix1.length; i++) {
            int g1=getGrayscale(pix1[i]);
            int g2=getGrayscale(pix2[i]);
            int grayColor = getGrayColor(g1, g2);
            pix3[i]=grayColor;
        }
        bitmap1.setPixels(pix3,0, with,0,0, with, height);
        return bitmap1;
    }

    /**
     * 获取灰度值
     * @param color
     * @return
     */
    public static int getGrayscale(int color){
        int a = Color.alpha(color);
        int dl=255-a;
        int r = Color.red(color)*a/255+dl;
        int g = Color.green(color)*a/255+dl;
        int b = Color.blue(color)*a/255+dl;
        return (int) (0.3 * r + 0.59 * g + 0.11 * b);
    }

    /**
     *
     * @param gray
     * @param gray2
     * @return
     */
    private static int getGrayColor(int gray, int gray2) {
        float a = (255 + gray2 - gray) * 1.0f / 255;
        int t = (int) (gray2 * 1.0f / a);
        return Color.argb((int) (a * 255 / 2), t, t, t);
    }

}
